<?php

namespace app\model;

use app\ConstVar;

class SmsCodeModel extends ActionBaseModel
{
    protected $name = 'sms_code';

    //入库
    public function addSmsCode(string $strPhone, string $strCode): bool
    {

        if (empty($strPhone) || empty($strCode)) {
            return false;
        }
        $modelSmsCode = new self();

        //如果已经存在，则更新
        $arrInfo = self::getOneByWhere([['phone', '=', $strPhone]]);
        if (!empty($arrInfo)) {
            $modelSmsCode->updateOneByWhere(
                [['phone', '=', $strPhone]],
                [
                    'code' => $strCode,
                    'expire_time' => time() + ConstVar::SMS_VERIFY_CODE_PERIOD,
                    'create_time' => date('Y-m-d H:i:s')
                ]
            );
            return true;
        }

        //不存在，插入新记录
        $arrInsertData = [
            'phone' => $strPhone,
            'code' => $strCode,
            'expire_time' => time() + ConstVar::SMS_VERIFY_CODE_PERIOD,
            'create_time' => date('Y-m-d H:i:s')
        ];
        $intLow = $modelSmsCode->insertOne($arrInsertData);
        if (empty($intLow)) {
            return false;
        }
        return true;
    }
}
